import axios from "axios";
import { useRouter } from "vue-router";
import { message } from 'ant-design-vue';
const env = process.env.NODE_ENV;
switch (env) {
  case "development":
    axios.defaults.baseURL = "";
    break;
  case "debug":
    axios.defaults.baseURL = "";
    break;
  case "production":
    axios.defaults.baseURL = "";
    break;
  default:
    break;
}
const baseURL = "";
const api = axios.create({
  baseURL:baseURL,
  timeout: 10000,
});

api.interceptors.request.use(
  (config) => {
    // 如果开启 token 认证
    if (localStorage.getItem("token")) {
      config.headers["Authorization"] =
        "Bearer " + localStorage.getItem("token"); // 请求头携带 token
    }
    if (config.method === "get" && config.data) {
      let param = ''
      for (let [k, v] of Object.entries(config.data)) {
        param += '&' + k + '=' + v
      }
      config.url = config.url.indexOf('?') > -1 ? config.url + param : config.url + '?' + param.slice(1)
    }else
      // 设置请求头
    if (!config.headers["Content-Type"]) {
      // 如果没有设置请求头
      if (config.method === "post") {
        // config.headers["Content-Type"] = "application/x-www-form-urlencoded";  post 请求
        // config.data = qs.stringify(config.data); // 序列化,比如表单数据//
      } else {
        config.headers["Content-Type"] = "application/json"; // 默认类型
        if (config.data) {
          let param = ''
          for (let [k, v] of Object.entries(config.data)) {
            if (v || v == '0') {
              param += `${k}=${v}&`
            }
          }
          if (param) {
            param = param.slice(0, -1)
            config.url = config.url.indexOf('?') == -1 ? config.url + `?${param}` : config.url + `&${param}`
          }
        }
      }
    }
    console.log("请求配置", config.url);
    return config;
  },
  (error) => {
    Promise.reject(error);
  }
);

api.interceptors.response.use(
  (res) => {
    let data = res.data;
    if (data.code == 200) {
      return data.data;
    } else if (data.code == 401) {
      ElMessage({
        type: "error",
        duration: 5000,
        message: "您未登录，或者登录已经超时，请先登录！",
      });
      localStorage.clear();
      const router = useRouter();
      router.push("/login");
      return "";
    } else if (data.message) {
      message.error(data.message + (typeof data.data == "string" ? "," + data.data : ""));
      return "";
    } else {
      return res;
    }
  },
  (error) => {
    console.log('===================================error===========================', error.response)
    let message = "";
    if (error.code == "ECONNABORTED") {
      message = '网络连接失败'
    }
    if (error && error.response) {
      switch (error.response.status) {
        case 302:
          message = "接口重定向了！";
          break;
        case 400:
          message = "参数不正确！";
          break;
        case 401:
          message = "您未登录，或者登录已经超时，请先登录！";
          message.error(message);
          localStorage.clear();
          const router = useRouter();
          router.push("/login");
          break;
        case 403:
          message = "您没有权限操作！";
          break;
        case 404:
          message = `请求地址出错: ${error.response.config.url}`;
          break;
        case 408:
          message = "请求超时！";
          break;
        case 409:
          message = "系统已存在相同数据！";
          break;
        case 500:
          let u = error.response.config.url;
          if (u.indexOf('/api/back/goveruser/import') != -1
            || u.indexOf('/api/back/schoolteachers/import') != -1
            || u.indexOf('/api/back/schoolstudents/import') != -1
            || u.indexOf('/api/back/potential/import') != -1
            || u.indexOf('/api/back/goveruser/import') != -1
          ) {
            message = "导入数据失败，可能是网络问题、数据量超出限制或填写格式有误。请重新检查后导入。";
          } else {
            message = "此刻服务器在小憩，待它苏醒再服务。";
          }
          break;
        case 501:
          message = "服务未实现！";
          break;
        case 502:
          message = "网关错误！";
          break;
        case 503:
          message = "服务不可用！";
          break;
        case 504:
          message = "服务暂时无法访问，请稍后再试！";
          break;
        case 505:
          message = "HTTP 版本不受支持！";
          break;
        default:
          message = "异常问题，请联系管理员！";
          break;
      }
    }
    if (message) {
      message.error(message)
    }

    return '';
  }
);

export default api;
